<template>
  <div class="course">
    <!-- 搜索部分 -->
    <el-row :gutter="10" class="search-section">
      <el-col :span="5">
        <el-form-item label="租户标识：">
          <el-input v-model="filters.companyId" placeholder="请输入租户标识"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="联系人：">
          <el-input v-model="filters.contacts" placeholder="请输入联系人"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="电话：">
          <el-input v-model="filters.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="租户名称：">
          <el-input v-model="filters.company_name" placeholder="请输入租户名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="search" :icon="Search">搜索</el-button>
        <el-button @click="reset" :icon="Refresh">重置</el-button>
      </el-col>
    </el-row>

    <!-- 按钮部分 deleteSelectedNews-->
    <div class="button-section">
      <el-button type="primary" plain :icon="Plus" @click="openAddDialog">新增</el-button>
      <el-button type="success" plain :icon="Edit" @click="editSelectedMeeting">修改</el-button>
      <el-button type="danger" plain :icon="Delete" @click="deleteSelectedMeeting">删除</el-button>
      <el-button type="warning" plain :icon="Download" @click="exportExcle">导出</el-button>
    </div>

    <!-- 租户列表表格 -->
    <el-table :data="companyListWithPagination" style="width: 100%" ref="multipleTable"
      @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="companyId" label="租户标识" width="150"></el-table-column>
      <el-table-column prop="contacts" label="联系人" width="150"></el-table-column>
      <el-table-column prop="tel" label="电话" width="220"></el-table-column>
      <el-table-column prop="companyName" label="租户名称" width="220"></el-table-column>
      <el-table-column prop="name" label="管理员" width="180"></el-table-column>

      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" @click="editCompany(scope.$index, scope.row)" link size="small"
              :icon="EditPen">修改</el-button>
            <el-button type="primary" @click="deleteCompany(scope.$index, scope.row)" link size="small"
              :icon="Delete">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination class="pagination-fixed" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pageination.currentPage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="pageination.pageSize"
        layout="total, sizes, prev, pager, next" :total="pageination.total"> <!--  style="text-align: center;" -->
      </el-pagination>
    </div>
    <!-- 添加资讯 -->
    <el-dialog v-model="visible" title="添加租户" width="70%" @close="resetForm()">
      <div>
        <el-form :model="addFormData" :rules="rules" ref="ruleForm">
          <el-form-item label="租户名称" prop="company_name" style="width: 500px;">
            <el-input v-model="addFormData.company_name" placeholder="请输入租户名称"></el-input>
          </el-form-item>
          <el-form-item label="租户图标" prop="image">
            <el-upload class="upload-demo" ref="upload" action="http://localhost:9000/upload"
              :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :file-list="fileList"
              list-type="picture-card" :on-success="handleUploadSuccess" :limit="1" :on-exceed="handleExceed" draggable>

              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item style="margin-top: 0px;">
            <div slot="tip" class="el-upload__tip" style="margin-left: 60px;">文件大小不超过 5MB, 支持 png/jpg/jpeg 格式
            </div>
          </el-form-item>
          <el-dialog v-model="dialogVisible" style="width: 480px; height: auto;">
            <img :src="dialogImageUrl" style="width: 400px; height: auto;" />
          </el-dialog>

          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;联系人" prop="contacts">
            <el-input v-model="addFormData.contacts" placeholder="请输入联系人" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;电话" prop="phone">
            <el-input v-model="addFormData.phone" placeholder="请输入电话" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;管理员" prop="user_name">
            <el-input v-model="addFormData.user_name" placeholder="请输入管理员" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注" prop="content">
            <QuillEditorVue ref="quillEditor" :initial-content="addFormData.remark"
              @content-updated="handleContentUpdate">
            </QuillEditorVue>

          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改租户 -->
    <el-dialog v-model="visibleUpdate" title="编辑租户信息" width="70%" @close="resetForm">
      <div>
        <el-form :model="updateFormData" :rules="rules" ref="ruleForm">
          <el-form-item label="租户名称" prop="company_name" style="width: 500px;">
            <el-input v-model="updateFormData.company_name" placeholder="请输入租户名称"></el-input>
          </el-form-item>
          <el-form-item label="租户图标" prop="image">
            <el-upload class="upload-demo" ref="upload1" action="http://localhost:9000/upload"
              :on-preview="handlePreview1" :on-remove="handleRemove1" :before-remove="beforeRemove1"
              :file-list="fileList1" list-type="picture-card" :on-success="handleUploadSuccess1" :limit="1"
              :on-exceed="handleExceed1" draggable>
              <!-- 如果有图片URL，显示图片<el-icon><Plus /></el-icon> -->
              <img v-if="updateFormData.imageURL" :src="updateFormData.imageURL" class="avatar" />

            </el-upload>

          </el-form-item>
          <el-form-item style="margin-top: 0px;">
            <div slot="tip" class="el-upload__tip" style="margin-left: 60px;">文件大小不超过 5MB, 支持 png/jpg/jpeg 格式
            </div>
          </el-form-item>
          <el-dialog v-model="dialogVisible1" style="width: 480px; height: auto;">
            <img :src="dialogImageUrl1" style="width: 400px; height: auto;" />
          </el-dialog>
          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;联系人" prop="contacts">
            <el-input v-model="updateFormData.contacts" placeholder="请输入联系人" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;电话" prop="phone">
            <el-input v-model="updateFormData.phone" placeholder="请输入电话" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;管理员" prop="user_name">
            <el-input v-model="updateFormData.user_name" placeholder="请输入管理员" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注" prop="content">
            <QuillEditorVue ref="quillEditor1" :initial-content="updateFormData.remark"
              @content-updated="handleContentUpdate1">
            </QuillEditorVue>
          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleUpdate = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitEditForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, Ref, onMounted, reactive } from 'vue';
import { Plus, Edit, Delete, Download, EditPen, Search, Refresh } from '../../../node_modules/@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { type Filters, type CompanyItem, type UserItem, getCompanyList, addCompanyService, editCompanyService, deleteCompanyService, exportFile, searchCompanyService } from '../../api/companyApi'
import QuillEditorVue from '../../components/commonUse/Editor.vue';
import type { UploadProps, UploadUserFile, UploadRawFile, FormInstance } from 'element-plus'
import { getUserList } from '../../api/userApi.ts';


const filters: Ref<Filters> = ref({
  company_name: '',
  contacts: '',
  phone: '',
  companyId:  null
});
const companyList: Ref<UserItem[]> = ref([]);
const companyListWithPagination: Ref<UserItem[]> = ref([]);
// 租户列表
const fetchCompanyList = async () => {
  const res = await getCompanyList();
  companyList.value = res;
  pageination.total = companyList.value.length;
  handleCurrentChange(1);
  handleSizeChange(10);
};
fetchCompanyList();
// 搜索功能
const search = async () => {

  companyList.value = await searchCompanyService(filters.value);
  pageination.total = companyList.value.length;
  handleCurrentChange(1);
  handleSizeChange(10);
  ElMessage.success('搜索成功！');

};

//重置搜索条件
const reset = () => {
  filters.value = {
    company_name: '',
    contacts: '',
    phone: '',
    companyId:  null
  };
  fetchCompanyList();
  
};

//添加资讯
const visible = ref(false);

const addFormData = ref<CompanyItem>({
  companyId: 0,
  company_name: '',
  user_name: '',
  imageURL: '',
  phone: '',
  contacts: '',
  remark: '',
});
const openAddDialog = () => {
  isAddForm.value = true;
  visible.value = true;
  resetForm(); // 打开对话框时重置表单

};
//图片预览
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const upload = ref(); // 引用上传组件
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url; // 确保设置正确的图片URL
  dialogVisible.value = true;
};
//更新富文本编辑器内容
const quillEditor = ref(null);
const handleContentUpdate = (newContent: string) => {
  addFormData.value.remark = newContent;
}

//上传封面图片

const fileList: Ref<UploadRawFile[]> = ref([]);
const handleRemove = (file: any, fileList: any) => {
  //用户点击移除按钮,先执行beforeRemove1中的逻辑，再执行handleRemove1中的逻辑
  addFormData.value.imageURL = fileList.length > 0 ? fileList[0].url : '';
};
const beforeRemove = async (file: any, fileList: any) => {
  try {
    await ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    return true;
  } catch (e) {
    console.error('Remove cancelled', e);
    return false;
  }
};

const handleUploadSuccess = (response: any, file: any, fileList: any) => {
  addFormData.value.imageURL = response.data; // 假设 response.data 是图片 URL
  file.url = response.data; // 更新fileList中的文件URL，确保预览是正确的
};
// 超过文件限制处理函数
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value.clearFiles(); // 清除现有文件
  const newFile = files[0] as UploadRawFile;
  upload.value.handleStart(newFile); // 手动添加文件到上传队列
  fileList.value.push(newFile); // 更新文件列表
};
// 实现提交功能
const submitForm = async () => {
  if (ruleForm.value) {
    ruleForm.value.validate(async (valid: any) => {
      console.log("enter")
      if (valid) {
        try {
          // 调用添加租户的接口
          const res = await addCompanyService(addFormData.value);
          console.log(res);
          if (res.code == 0 || res.isOk == true) {
            ElMessage.success('提交成功！');
            visible.value = false;
            // 提交后清空表单
            resetForm();
            fetchCompanyList();
          } else {
            ElMessage.error(res.msg);
          }
          isShown.value = false//ELMessage解锁
        } catch (error) {
          console.error(error)
        }

      } else {
        ElMessage({
          message: '请提交正确的租户信息!',
          type: 'error',
        });
        return false;
      }
    });
  }
};

//重置表单
const resetForm = async () => {
  addFormData.value = {
    companyId:  null,
    company_name: '',
    user_name: '',
    imageURL: '',
    phone: '',
    contacts: '',
    remark: '',

  };
  // 清除上传组件的文件列表
  if (upload.value) {
    upload.value.clearFiles();
  }
  // 清除上传组件的文件列表
  if (upload1.value) {
    upload1.value.clearFiles();
  }
  updateFormData.value = {
    companyId:  null,
    company_name: '',
    user_name: '',
    imageURL: '',
    phone: '',
    contacts: '',
    remark: ''
  };
  if (ruleForm.value) {
    ruleForm.value.resetFields(); // 重置表单字段和验证状态
  }
  isAddForm.value = true;          // 重设为添加模式
  isShown.value = false;           // 重置错误消息显示锁
  
};

//修改资讯
const visibleUpdate = ref(false);
const updateFormData = ref<CompanyItem>({
  companyId:  null,
  company_name: '',
  user_name: '',
  imageURL: '',
  phone: '',
  contacts: '',
  remark: ''
});
//更新富文本编辑器内容
const quillEditor1 = ref(null);
const handleContentUpdate1 = (newContent: string) => {
  updateFormData.value.remark = newContent;

}
//上传封面图片
const fileList1: Ref<UploadRawFile[]> = ref([]);
//图片预览
const dialogImageUrl1 = ref('');
const dialogVisible1 = ref(false);
const upload1 = ref(); // 引用上传组件
const handlePreview1: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl1.value = uploadFile.url!;
  dialogVisible1.value = true;
};

//删除封面图片
const handleRemove1 = (file: any, fileList: any) => {
  //用户点击移除按钮,先执行beforeRemove1中的逻辑，再执行handleRemove1中的逻辑
  updateFormData.value.imageURL = fileList.length > 0 ? fileList[0].url : '';
};

const beforeRemove1 = async (file: any, fileList: any) => {
  try {
    await ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    return true;
  } catch (e) {
    console.error('Remove cancelled', e);
    return false;
  }
};

const handleUploadSuccess1 = (response: any, file: any, fileList: any) => {
  updateFormData.value.imageURL = response.data; // 假设 response.data 是图片 URL
  file.url = response.data; // 更新fileList中的文件URL
};

const handleExceed1: UploadProps['onExceed'] = (files) => {
  upload1.value.clearFiles(); // 清除现有文件
  const newFile = files[0] as UploadRawFile;
  upload1.value.handleStart(newFile); // 手动添加文件到上传队列
  fileList1.value.push(newFile); // 更新文件列表
};

//编辑
const editCompany = async (index: number, row: UserItem) => {
  //做一个数据处理，将row的数据赋值给updateFormData
  await nextTick();
  isAddForm.value = false;
  updateFormData.value = {
    companyId: row.companyId,
    company_name: row.companyName,
    user_name: row.name,
    imageURL: row.imageURL,
    phone: row.tel,
    contacts: row.contacts,
    remark: row.remark
  };
  handleContentUpdate1(row.remark);
  visibleUpdate.value = true;
};
//提交修改资讯的表单
const submitEditForm = async () => {
  if (ruleForm.value) {
    ruleForm.value.validate(async (valid: any) => {
      
      if (valid) {
        try {
          const res = await editCompanyService(updateFormData.value);
          if (res.code == 0 || res.isOk == true) {
            ElMessage.success('修改成功！');
            visibleUpdate.value = false;
            // 提交后清空表单
            resetForm(); reset();
            fetchCompanyList();
          } else {
            ElMessage.error(res.msg);
          }
        } catch (error) {
          console.error('Login failed:', error)
          // 可以在这里添加错误处理，例如显示错误消息给用户
        }

      } else {
        ElMessage({
          message: '请提交正确的租户信息!',
          type: 'error',
        });
        return false;
      }
    });
  }
};
//删除租户
const deleteCompany = async (index: number, row: UserItem) => {
  //获取租户名称
  const name = row.companyName;
  const id = row.companyId;
  ElMessageBox.confirm('确定删除该 "' + name + '" 的租户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 实现删除功能
    const res = await deleteCompanyService(id);
    if (res.code == 0 || res.isOk == true) {
      ElMessage.success('删除成功！');
      fetchCompanyList();
      reset();
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });

};
//选择条目功能
//不能实现批量添加，修改，只能对选中的第一条数据进行操作
//可以实现批量删除
const selectedRows = ref<UserItem[]>([]);
const handleSelectionChange = (selection: UserItem[]) => {
  selectedRows.value = selection;
};
const editSelectedMeeting = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要编辑的新闻');
    return;
  }

  //选取第一条选中的租户进行编辑
  editCompany(0, selectedRows.value[0]);

};
const deleteSelectedMeeting = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的新闻');
    return;
  }
  // 遍历选中的所有咨询条目，并逐个执行删除操作
  for (const row of selectedRows.value) {
    const id = row.companyId;
    try {
      await deleteCompanyService(id);

    } catch (error) {
      ElMessage.error('删除失败！');
    }
  }
  ElMessage.success('删除成功！');
  fetchCompanyList();

};
//导出excel
const exportExcle = () => {
  exportFile();
  ElMessage.success('导出成功！');
};

//表单验证
const users = ref<any>([]);
const isShown = ref(false)//ELMessage解锁(创建者)
onMounted(async () => {
  users.value = await getUserList();
});
//表单选择
const isAddForm = ref(true)
// const userNames = ref<String[]>([]);
const ruleForm = ref<FormInstance>()
const rules = {
  company_name: [
    { required: true, message: '请输入租户名称！', trigger: 'blur' }
  ],
  contacts: [
    { required: true, message: '请输入联系人！', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        const isGet = ref(false);
        users.value.forEach((user: UserItem) => {
          if (user.name == value&&isAddForm.value==true) {
            isGet.value = true;
            callback('输入的管理员已经存在');
            if (isShown.value == false) {
              ElMessage({
                message: '输入的管理员已经存在！或者尝试刷新页面',
                type: 'error',
              });
              isShown.value = true;//ELMessage加锁
            }
            return false;
          }
        })
        callback();
        return true;

      }, trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入联系方式！', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        const reg = /^\d{11}$/; // 正则表达式匹配 11 位数字
        if (value && reg.test(value)) {
          callback(); // 验证通过
        } else {
          callback(new Error('请输入11位手机号')); // 验证不通过，返回错误信息
        }
      }
    }
  ],
  user_name: [
    { required: true, message: '请输入管理员！', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        const isGet = ref(false);
        users.value.forEach((user: UserItem) => {
          if (user.name == value&&isAddForm.value==true) {
            isGet.value = true;
            callback('输入的管理员已经存在');
            if (isShown.value == false) {
              ElMessage({
                message: '输入的管理员已经存在！或者尝试刷新页面',
                type: 'error',
              });
              isShown.value = true;//ELMessage加锁
            }
            return false;
          }
        })
        callback();
        return true;

      }, trigger: 'blur'
    }
  ]
}

//分页
const pageination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 64
});
//当每页条数发生了变化，调用此函数
const handleSizeChange = (val: number) => {
  pageination.pageSize = val;
  companyListWithPagination.value = companyList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
//当前页码发生变化，调用此函数
const handleCurrentChange = (val: number) => {
  pageination.currentPage = val;
  companyListWithPagination.value = companyList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
</script>

<style scoped>
.course {
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 1200px;
  padding: 20px;
  margin: 0 auto;
}

.search-section {
  margin-bottom: 0px;
  width: 100%;
}

.button-section {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

.upload-demo .el-upload__tip {
  font-size: 12px;
  line-height: 1.0;
  margin-top: 0px;
}

.avatar-uploader-icon {
  border: 1px dashed var(--el-border-color);
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 158px;
  text-align: center;
}

.avatar {
  width: 100%;
  /* 根据需要调整尺寸 */
  height: auto;
  cursor: pointer;
}

.pagination-fixed {
  text-align: center;
}

.pagination-container {
  /* position: fixed; */
  display: flex;
  margin-top: 25px;
  /* margin-bottom: -2000px; */
  justify-content: center;
  width: 100%;
  z-index: 1000;
  /* 确保分页条在最上层 */
}
</style>
